/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.unice.miage.oobdoo.manager;

import com.unice.miage.oobdoo.entity.Album;
import com.unice.miage.oobdoo.entity.Note;
import com.unice.miage.oobdoo.entity.Utilisateur;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Remi
 */
@Stateless
public class NoteManager {
    
    @PersistenceContext
    private EntityManager em;

    public Note creerNote(Utilisateur u, Album a, int s)
    {
        Note n = new Note(u,a,s);
        em.persist(n);
        return n;
    }

    public Note getNoteByAlbumAndUser(Album a , Utilisateur u )
    {
        String qlString = "select n from Note n where n.auteur = :a and n.album = :b";
        try{
            Query q = em.createQuery(qlString);
            q.setParameter("a", u);
            q.setParameter("b", a);
            return (Note) q.getSingleResult();
        } catch(NoResultException ex){
            return null;
        }
        catch(Exception e)
        {
            System.err.println("exception=" + e.getClass());
            return null;
        }
        
    }

    public boolean checkIfNoteExist(Album a, Note n)
    {
        Collection<Note> notes = a.getNotes();
        for(Note i : notes)
        {
            if(i.getAuteur().getId() == n.getAuteur().getId() && i.getAlbum().getId() == n.getAlbum().getId())
            {
                return true;
            }
        }
        return false;
    }

    public void updateNote(Note n, int score)
    {
        n.setValue(score);
        em.merge(n);
    }
    
    public void deleteNote(Note n)
    {
        try {
            em.remove(em.merge(n));
        } catch (Exception ex) {
            System.err.println("CommentaireManager.deleteCommentaire, exception=" + ex);
        }
    }
}
